package com.tanhua.server.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tanhua.commons.utils.Constants;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.service.UserFreezeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;

@Service
public class UserFreezeServiceImpl implements UserFreezeService {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 判断用户是否被冻结，如果已经被冻结，抛出异常即可
     * 参数：冻结范围，用户ID
     */
    @Override
    public void checkStatus(Long userId, String freezingRange) {
        //拼接key，从Redis中查数据
        String key = Constants.USER_FREEZE+userId;
        String value = redisTemplate.opsForValue().get(key);
        //如果存在，且冻结范围一致，则抛出异常
        if (!StringUtils.isEmpty(value)){
            Map map = JSON.parseObject(value,Map.class);
            String range = (String) map.get("freezingRange");
            if (freezingRange.equals(range) ){
                throw new BusinessException(ErrorResult.builder().errMessage("用户已被冻结").build());
            }
        }

    }


}
